package multiplayerShooter;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import multiplayerShooter.Player.Direction;

public class Bullet implements Runnable, Printable {
	private int x;
	private int y;
	private int change;
	private Player opponent;

	public Bullet(int x_, int y_, int change_, Player opponent_) {
		this.x = x_;
		this.y = y_;
		this.opponent = opponent_;
		this.change = change_ * 5;
		Thread b = new Thread(this);
		b.start();
	}

	public Bullet(Player theKiller) {
		if(theKiller.getDirection()==Direction.LEFT)
		{
			x =theKiller.getXPos() + 9;
			y =theKiller.yPos + 12;
			change = -5;
		}
		else
		{
			x =theKiller.getXPos() + 66;
			y =theKiller.yPos + 12;
			change = 5;
		}
		
		ArrayList<Player> opponents = new ArrayList<Player>(theKiller.getAllPlayers());
		opponents.remove(theKiller);
		opponent = opponents.get(0);		
	}

	public void run() {
		while (this.x > 0 && this.x < 1024) {
			this.x += this.change;
			try {
				Thread.sleep(6);
			} catch (Exception e) {
			}	
			if (opponent!=null && this.x > this.opponent.getXPos() + 25 && this.x < this.opponent.getXPos() + 70
					&& this.y > this.opponent.yPos
					&& this.y < this.opponent.yPos + 84
					&& this.opponent.getHealth() > 0) {
				if(this.opponent.getXPos()+change * 2>0&&this.opponent.getXPos()+change * 2<1024-77)
					this.opponent.setXPos(this.opponent.getXPos() + this.change * 2);
				this.opponent.setHealth(this.opponent.getHealth() - 1);

				if (this.opponent.getHealth() <= 0) {
					this.opponent.respawn();
				}
				this.x = -5;// Move Off Screen to kill loop
			}

		}
		this.change = 0;
	}

	public void draw(Graphics g) {
		g.setColor(new Color(157, 20, 20));
		g.fillOval(x, y, 8, 4);
		
	}

	public boolean printItem() {
		// TODO Auto-generated method stub
		return change!=0;
		
	}

	public Thread fire() {
		Thread shoot = new Thread(this);
		shoot.start();
		return shoot;
	}
}